﻿using OPC.DataBase.BLL;
using OPC.DataBase.Models;
using OPCAutomation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OPC.DataBase.UI
{
    public class OPCClient
    {
        public static OPCServer Server;
        public static OPCGroup Group;

        public static Dictionary<long, OPCINFO> Data = new Dictionary<long, OPCINFO>();

        /// <summary>
        /// 启动
        /// </summary>
        /// <returns></returns>
        public static OPCGroup Start()
        {
            if (Server == null)
            {
                Server = new OPCServer();
                Server.Connect("KEPware.KEPServerEx.V4");
                if (Server.ServerState == Convert.ToInt32(OPCServerState.OPCRunning))
                {
                    var Groups = Server.OPCGroups;
                    Groups.DefaultGroupDeadband = 0;
                    Groups.DefaultGroupIsActive = true;
                    Groups.DefaultGroupUpdateRate = 10;
                    Group = Groups.Add("Group");
                    Group.IsSubscribed = true;
                    var Items = Group.OPCItems;
                    var ItemInfos = GetOPCInfo();
                    foreach (var item in ItemInfos)
                    {
                        var o = Items.AddItem(item.TAG, (int)item.CLIENTHANDLE);
                        item.ITEM = o;
                        Data.Add(item.CLIENTHANDLE, item);
                    }
                }
                return Group;
            }
            else
            {
                if (Server.ServerState != Convert.ToInt32(OPCServerState.OPCRunning))
                {
                    Server.Connect("KEPware.KEPServerEx.V4");
                }
                return Group;
            }
        }

        /// <summary>
        /// 关闭
        /// </summary>
        public static void DisConnect() {
            if (Server.ServerState == Convert.ToInt32(OPCServerState.OPCRunning))
            {
                Server.Disconnect();
            }
        }

        /// <summary>
        /// 获取数据库配置信息
        /// </summary>
        /// <returns></returns>
        private static List<OPCINFO> GetOPCInfo()
        {
            OPCInfoService service = new OPCInfoService();
            var sql = "select * from OPCINFO";
            var result = service.Query(sql);
            return result;
        }
    }
}
